<template>
  <div class="password-management">
    <div class="header">
      <h2>密码管理</h2>
      <p>管理员可以在此修改用户的密码</p>
    </div>
    
    <!-- 搜索用户 -->
    <div class="toolbar">
      <el-card class="search-card">
        <el-row :gutter="20" align="middle">
          <el-col :span="16">
            <div class="search-fields">
              <el-input
                v-model="searchForm.username"
                placeholder="请输入用户名"
                style="width: 200px; margin-right: 10px"
                clearable
                prefix-icon="el-icon-search"
              />
              <el-button type="primary" @click="searchUsers">
                <i class="el-icon-search"></i>
                搜索
              </el-button>
              <el-button @click="resetSearch">
                <i class="el-icon-refresh"></i>
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 用户列表 -->
    <div class="user-table">
      <el-card>
        <el-table
          :data="userList"
          border
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="role" label="角色" width="150">
            <template #default="scope">
              <span v-if="scope.row.role === 'ADMIN'">系统管理员</span>
              <span v-else-if="scope.row.role === 'LECTURER'">讲师</span>
              <span v-else-if="scope.row.role === 'STUDENT'">学生</span>
              <span v-else-if="scope.row.role === 'AUDITOR'">审计员</span>
              <span v-else>{{ scope.row.role }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <el-button size="small" @click="showPasswordDialog(scope.row)">
                <i class="el-icon-edit"></i>
                修改密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改用户密码"
      v-model="passwordDialogVisible"
      width="500px"
      @close="handlePasswordDialogClose"
    >
      <el-form
        :model="passwordForm"
        :rules="passwordFormRules"
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="selectedUser.username" disabled />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="selectedUser.name" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUserPassword">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import { useRouter } from 'vue-router'

// 定义响应式数据
const userList = ref([])
const loading = ref(false)
const passwordDialogVisible = ref(false)
const router = useRouter()

// 搜索表单
const searchForm = reactive({
  username: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 密码表单
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 选中的用户
const selectedUser = ref({})

// 表单验证规则
const passwordFormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const passwordFormRef = ref()

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/users', {
      params: {
        page: pagination.currentPage - 1, // Spring Data JPA页面从0开始，前端从1开始
        size: pagination.pageSize,
        username: searchForm.username
      }
    })
    
    userList.value = response.data.content
    pagination.total = response.data.totalElements
  } catch (error: any) {
    if (error.response && error.response.status === 403) {
      ElMessage.error('权限不足，请重新登录')
      // 清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      router.push('/login')
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 搜索用户
const searchUsers = () => {
  pagination.currentPage = 1
  fetchUsers()
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  pagination.currentPage = 1
  fetchUsers()
}

// 处理分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.currentPage = 1 // 重置到第一页
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchUsers()
}

// 显示密码修改对话框
const showPasswordDialog = (user: any) => {
  selectedUser.value = user
  passwordDialogVisible.value = true
  // 重置表单
  Object.assign(passwordForm, {
    newPassword: '',
    confirmPassword: ''
  })
}

// 处理密码对话框关闭
const handlePasswordDialogClose = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 更新用户密码
const updateUserPassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await request.put(`/api/users/${selectedUser.value.id}/password`, {
          newPassword: passwordForm.newPassword
        })
        ElMessage.success('密码更新成功')
        passwordDialogVisible.value = false
      } catch (error: any) {
        if (error.response && error.response.status === 403) {
          ElMessage.error('权限不足，请重新登录')
          // 清除本地存储并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          router.push('/login')
        } else {
          ElMessage.error('密码更新失败: ' + (error.response?.data?.message || '未知错误'))
        }
      }
    }
  })
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.password-management {
  padding: 0;
  background-color: #f5f7fa;
  min-height: 100%;
  width: 100%;
  height: 100%;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  color: #303133;
  margin-bottom: 5px;
}

.header p {
  color: #606266;
  margin: 0;
}

.toolbar {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 0;
}

.search-fields {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.user-table {
  margin-bottom: 0;
}

.user-table :deep(.el-card) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-table :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
}
</style>